// miniprogram/pages/prodetail/prodetail.js
const app = getApp();
const { goodsDetail, goodsRelated, cartAdd, collectAddordelete } = require('../../utils/api.js');
const WxParse = require('./../wxParse/wxParse.js');
const token_req = require('../../utils/myRequest.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //scroll-view的高度
    scrollHeight: 0,
    //是否允许竖向滚动
    isScroll_y: true,
    //显示
    //显示产品参数
    showAttribute: false,
    //显示产品服务
    showIssue: false,
    //显示规格参数
    showSpecification: false,
    //默认购买商品的数量
    prodNum: 1,
    starGroup:{
      hasStar: false,
      //收藏icon(默认灰色)
      starImage: '../../images/star_active.png',
      starText: 'color: rgb(226, 70, 70)'
    },
    //是否开始加载富文本
    isLoad_richText: true
  },

  //请求当前产品数据
  req_Data(pro_id){
    //请求次数
    let i = 0;
    token_req.myRequest({
      url: goodsDetail,
      data: {
        id: pro_id
      },
      success: (res) => {
        console.log(res);
        //获取详情长图等信息
        let info = res.data.data.info;
        //获取轮播图片
        let gallery = res.data.data.gallery;
        //产品特性
        let attribute = res.data.data.attribute;
        //用户是否已收藏
        let userHasCollect = res.data.data.userHasCollect;
        //产品配套服务
        let issue = res.data.data.issue;
        //评论数据
        let comment = res.data.data.comment;
        // 所属品牌
        let brand = res.data.data.brand;
        //规格(选择商品的颜色/大小等)
        let specificationList = res.data.data.specificationList;
        //不同规格对应的价格
        let productList = res.data.data.productList;
        //初始化 规格选项的激活状态，默认选中第一个
        let spec_active = [];
        //规格的字符串描述
        let general_desc = [];
        if (specificationList.length > 0){
          specificationList.forEach((ele1, index1) => {
            let tempArr = {
              currIndex: 0,
              active: []
            }
            ele1.valueList.forEach((ele2, index2) => {
              if (index2 == 0) {
                tempArr.active.push('active');
                tempArr.id = ele2.id;
                general_desc.push(ele2.value);
              } else {
                tempArr.active.push('');
              }
            });
            spec_active.push(tempArr);
          });
        }
        //根据默认选中的规格组合 渲染数据(默认第一个)
        let choose_goods = productList[0];
        if (general_desc.length > 0){
          general_desc = general_desc.join(' ')
        }else{
          general_desc = '默认参数'
        }

        this.setData({
          gallery,
          info,
          attribute,
          issue,
          comment,
          brand,
          specificationList,
          productList,
          spec_active,
          spec_listIndex: 0,
          choose_goods,
          general_desc: general_desc
        });
      },
      fail(err){
        //超过5次就中断请求
        // if (i >= 5){
        //   wx.showToast({
        //     title: '连接超时!',
        //     duration: 1500,
        //   })
        //   return
        // }
        // console.log(err);
        // //重新发送请求
        // this.req_Data();
      }
    })
  },
  //请求关联产品集合
  req_relatedData(pro_id){
    //请求次数
    let i = 0;
    token_req.myRequest({
      url: goodsRelated,
      data: {
        id: pro_id
      },
      success:(res)=>{
        let related_proList = res.data.data.goodsList;
        this.setData({
          related_proList
        })
      },
      fail:()=>{
        //超过5次就中断请求
        // if (i >= 5){
        //   wx.showToast({
        //     title: '连接超时!',
        //     duration: 1500,
        //   })
        //   return
        // }
        // console.log(err);
        // //重新发送请求
        // this.req_Data();
      }
    });
  },
  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取商品id
    let pro_id = options.id;
    //测试用
    // pro_id = 1181000;
    //向后台请求数据
    this.req_Data(pro_id);
    this.req_relatedData(pro_id);
    //获取设备高度
    const systemInfo = wx.getSystemInfoSync();
    const curr_height = systemInfo.windowHeight - 50;
    const curr_dpr = systemInfo.pixelRatio;
    console.log('height:', curr_height, 'DPR:', curr_dpr);
    //初始化
    //设置scroll-view 内容容器的高度
    this.setData({
      scrollHeight: curr_height - 3 + 'px'
    });
  },
  //滚动到关联商品的底部再渲染富文本
  toBottom(event){
    let scrollHeight = event.detail.scrollHeight;
    let scrollTop = event.detail.scrollTop;
    let scrollView_heigh = scrollHeight-scrollTop;
    let percent = scrollHeight / scrollTop;
    let refrashHeight = scrollView_heigh/percent;
    let {isLoad_richText} = this.data;
    if (scrollTop >= refrashHeight && isLoad_richText){
      //解析富文本
      let goods_desc = this.data.info.goods_desc;
      const that = this;
      WxParse.wxParse('goods_desc', 'html', goods_desc, that, 0);

      this.setData({
        isLoad_richText: !isLoad_richText
      })
    }
  },
  //参数显示
  paramsShow(){
    this.setData({
      showAttribute: true,
      isScroll_y: false,
    });
  },
  //关闭参数
  closeParams(){
    this.setData({
      showAttribute: false,
      isScroll_y: true,
    });
  },
  //服务显示
  serverShow(){
    this.setData({
      showIssue: true,
      isScroll_y: false,
    })
  },
  //服务关闭
  closeServer(){
    this.setData({
      showIssue: false,
      isScroll_y: true,
    })
  },
  //规格显示
  specificationShow(){
    this.setData({
      showSpecification: true,
      isScroll_y: false,
    })
  },
  //规格关闭
  closeSpecification(){
    this.setData({
      showSpecification: false,
      isScroll_y: true,
    })
  },
  //选中某个规格参数，改变内部样式
  chooseSpec(event){
    // console.log(event);
    //对应集合组中 当前被选中某个集合的下标 ([1,2...])
    let spec_listIndex = event.currentTarget.dataset.listIndex;
    //在某个集合中 当前被选中元素的下标 ([[{id:1},{id:2}..],[{id:1}..]...])
    let spec_eleIndex = event.currentTarget.dataset.eleIndex;
    //获取某个集合中 上一个处于激活状态的下标
    let currIndex = this.data.spec_active[spec_listIndex].currIndex;

    //如果点击同一个规格就中断
    if (this.data.spec_eleIndex == currIndex){
      return;
    }

    //更新激活状态
    let spec_active = this.data.spec_active;
    //删除
    spec_active[spec_listIndex].active[currIndex] = '';
    //增加
    spec_active[spec_listIndex].active[spec_eleIndex] = 'active';
    //更新当前被选中元素的下标
    spec_active[spec_listIndex].currIndex = spec_eleIndex;
    
    //获取规格组合字符串 id1_id2
    let eleId = event.currentTarget.dataset.eleId;
    //更新id
    spec_active[spec_listIndex].id = eleId;
    //组合字符串(exam: 1_3)
    let general_spec = [];
    spec_active.forEach((ele)=>{
      general_spec.push(ele.id);
    });
    general_spec = general_spec.join('_');

    //文本字符串(exam: 1.5m床垫*1+枕头*2 浅杏粉)
    let general_desc = this.data.general_desc.split(' ');
    let specificationList = this.data.specificationList;
    general_desc[spec_listIndex] = specificationList[spec_listIndex].valueList[spec_eleIndex].value;

    //规格参数对应的价格 集合(大&红 -> ￥120)
    const productList = this.data.productList;
    // let choose_goods = {
    //   "id": '',
    //   //产品id
    //   "goods_id": '',
    //   //所选的规格组合
    //   "goods_specification_ids": "",
    //   "goods_sn": "",
    //   //库存
    //   "goods_number": '',
    //   //价格
    //   "retail_price": ''
    // }
    let choose_goods;
    for(let i=0,len = productList.length; i<len; i++){
      //如果匹配成功
      if (productList[i].goods_specification_ids == general_spec){
        choose_goods = productList[i];
        break;
      }
    }

    //重新渲染
    this.setData({
      spec_active,
      spec_listIndex,
      general_desc: general_desc.join(' '),
      choose_goods
    })
  },
  //减少购买数量
  prodNum_del(){
    let {prodNum} = this.data
    if(prodNum == 1){
      return;
    }
    this.setData({
      prodNum: --prodNum
    })
  },
  //增加购买数量
  prodNum_add(){
    let { prodNum } = this.data
    this.setData({
      prodNum: ++prodNum
    })
  },
  //确认 所选产品的规格和对应的数量
  sure_choose(){
    //关闭规格参数子页
    this.closeSpecification();
    //打开 开关 -> 渲染数据
    this.setData({
      has_sureChoose: true
    })
  },
  //收藏商品
  star(){
    // console.log("star");
    wx.showToast({
      icon: 'loading'
    });
    let { starGroup } = this.data;
    starGroup.hasStar = !starGroup.hasStar;
    this.setData({
      starGroup
    });
  
    if (starGroup.hasStar){
      let { choose_goods, prodNum } = this.data;
      token_req.myRequest({
        url: collectAddordelete,
        data: {
          typeId: 0,
          valueId: this.data.info.id,
        },
        method: 'POST',
        success: (res) => {
          wx.showToast({
            title: '收藏成功',
            icon: 'success',
            duration: 1500
          });
        },
        fail: (err) => {
          wx.showToast({
            title: err.errmsg,
            icon: 'none',
            image: '',
            duration: 2000,
          })
        }
      })
    }else{
      token_req.myRequest({
        url: collectAddordelete,
        data: {
          typeId: 0,
          valueId: this.data.info.id,
        },
        method: 'POST',
        success: (res) => {
          wx.showToast({
            title: '取消收藏',
            icon: 'none',
            duration: 1200
          });
        },
        fail: (err) => {
          wx.showToast({
            title: err.errmsg,
            icon: 'none',
            image: '',
            duration: 2000,
          })
        }
      })
    }
  },
  //加入购物车
  addToCart(){
    //如果没有选择规格
    if (!this.data.has_sureChoose){
      wx.showToast({
        title: '请选择物品规格',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    wx.showToast({
      title: '添加中...',
      icon: 'loading'
    });
    let { choose_goods,prodNum } = this.data;
    token_req.myRequest({
      url: cartAdd,
      data: {
        goodsId: choose_goods.goods_id,
        number: prodNum,
        productId: choose_goods.id
      },
      method: 'post',
      success:(res)=>{
        wx.showToast({
          title: '添加成功',
          icon: 'success',
          duration: 1500
        });
        console.log(res);
      },
      fail:(err)=>{
        fail: (err) => {
          wx.showToast({
            title: err.errmsg,
            icon: 'none',
            image: '',
            duration: 2000,
          })
        }
      }
    })
  },
  //跳转到关联产品
  to_relatedProd(event){
    let id = event.currentTarget.dataset.id;
    console.log(id);
    wx.navigateTo({
      url: `prodetail?id=${id}`,
    })
  },
})